<template>
  <div class="main">
    <!-- 数据查询区：表单 -->
    <el-form ref="queryRef" :model="queryParams" :inline="true">
      <el-form-item label="房型" prop="roomTypeId">
        <el-select
          v-model="queryParams.roomTypeId"
          style="width: 200px"
          placeholder="请选择房型"
          @change="handleQuery"
        >
          <el-option
            v-for="item in roomTypesOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="queryParams.status" @change="handleQuery">
          <el-radio-button label="空闲" />
          <el-radio-button label="已预定" />
          <el-radio-button label="已入住" />
          <el-radio-button label="打扫中" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="楼层" prop="floor">
        <el-input-number
          v-model.number="queryParams.floor"
          clearable
          style="width: 100px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="queryParams.date"
          type="date"
          placeholder="Pick a day"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
          disabled
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery(queryRef)">重置</el-button>
      </el-form-item>
    </el-form>
    <el-divider />
    <!-- 数据展示区：卡片 -->
    <el-row v-loading="loading" :gutter="7" style="margin-left: 5px">
      <el-col
        v-for="room in RoomsDataList"
        :key="room.id"
        :span="4"
        style="margin-bottom: 5px"
      >
        <el-card :style="cardStyle(room)">
          <template #header>
            <div class="card-header">
              <span style="font-size: 30px">{{ room.roomNumber }}</span>
              <el-popover
                v-if="room.status === '已入住'"
                v-loading="cardloading"
                placement="right"
                trigger="click"
                :width="250"
                :show-after="500"
                :hide-after="0"
              >
                <template #reference>
                  <el-icon
                    size="18"
                    class="hover-human"
                    @click="showInfoDialog(room.roomNumber)"
                  >
                    <UserFilled />
                  </el-icon>
                </template>

                <!-- Popover 内容 -->
                <div v-if="currentRoom" class="room-popover">
                  <h3>{{ currentRoom.roomNumber }}房间入住信息</h3>
                  <el-divider />
                  <div class="detail-item">
                    <label>联系人：</label>
                    <span>{{ currentRoom.contact }}</span>
                  </div>
                  <div class="detail-item">
                    <label>联系方式：</label>
                    <span>{{ currentRoom.phone }}</span>
                  </div>
                  <div class="detail-item">
                    <label>入住时间：</label>
                    <span>{{ currentRoom.startDate }}</span>
                  </div>
                  <div class="detail-item">
                    <label>预计离店：</label>
                    <span>{{ currentRoom.leaveDate }}</span>
                  </div>
                </div>
              </el-popover>
              <el-icon
                v-if="room.status === '打扫中'"
                size="18"
                style="margin-left: 90px"
                @click.stop="finishClean(room.roomNumber)"
              >
                <Brush />
              </el-icon>
              <br />
              <span>{{ room.name }}</span>
            </div>
          </template>
          <div>
            <p>状态: {{ room.status }}</p>
            <br />
            <p>
              价格: <span style="font-size: 20px">{{ room.finalPrice }}¥</span>
              <!-- <el-icon
                v-if="checkedOutRooms.includes(room.roomNumber)"
                size="18"
                style="margin-left: 50px; cursor: pointer"
                @click.stop="handleCheckOut(room.roomNumber)"
              >
                <CircleClose />
              </el-icon> -->
              <img
                v-if="checkedOutRooms.includes(room.roomNumber)"
                src="https://api.iconify.design/pepicons-pop:leave.svg"
                class="hover-scale"
                alt=""
                @click.stop="handleCheckOut(room.roomNumber)"
              />
            </p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据编辑区：入住表单 -->
    <el-dialog v-model="dialogOpen" :title="title" width="500">
      <!-- 前面是子组件,后面是本地 -->
      <RoomSaleForm
        :dialogOpen="dialogOpen"
        :roomNumber="roomNumber"
        @close="handleCloseDialog"
      />
    </el-dialog>
    <!-- 数据展示区：分页加载 -->
    <el-pagination
      v-model:page-size="queryParams.pageSize"
      v-model:current-page="queryParams.pageNum"
      style="margin-top: 20px"
      :page-sizes="[5, 10, 20, 30]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 数据编辑区：新增/修改对话框 默认不显示 -->
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRef, onMounted, computed } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { listAllRoomTypes } from "@/api/roomtypes";
import {
  getAllCheckOutStatus,
  getCheckOutStatus,
  getRoomCustomerInfo,
  listAllRooms,
  listRoomsPrice,
  roomCheckOut
} from "@/api/roomsale";
import type { RoomCheckOutStatus, RoomPriceDTO } from "@/api/roomsale";
import type { RoomTypesDTO } from "@/api/rooms";
import type { CustomerInfo, QueryParams } from "@/api/roomsale";
import RoomSaleForm from "@/views/hotel/roomsale/form.vue";
import { status } from "nprogress";
import axios from "axios";
onMounted(() => {
  // 挂载后加载数据
  getList();
  getRoomTypesOptions();
  getRoomCheckOutStatus();
});

const queryRef = ref<FormInstance>();
const roomTypesOptions = ref<RoomTypesDTO[]>([]);
const cardloading = ref<boolean>(false);
function getRoomTypesOptions() {
  listAllRoomTypes().then(response => {
    roomTypesOptions.value = response.data;
  });
}
const query = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 20,
  floor: undefined,
  status: undefined,
  roomTypeId: undefined,
  date: undefined
});
const queryParams = toRef(query);
// 数据查询区--> 查询按钮
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

const loading = ref<boolean>(false); // table数据加载遮罩
const total = ref<number>(0); // table数据总数
const RoomsData = reactive<RoomPriceDTO[]>([]); // table数据
const RoomsDataList = toRef(RoomsData);
const today = new Date();
queryParams.value.date =
  today.getFullYear() +
  "-" +
  String(today.getMonth() + 1).padStart(2, "0") +
  "-" +
  String(today.getDate()).padStart(2, "0");

async function getList() {
  loading.value = true;
  /** 调用后端分页查询接口 */
  listRoomsPrice(queryParams.value).then(response => {
    RoomsDataList.value = response.data.records;
    total.value = response.data.total;
    console.log("RoomsDataList", RoomsDataList.value);
  });
  loading.value = false;
}
const resetQuery = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  getList();
};

function cardStyle(room) {
  let backgroundColor;

  switch (room.status) {
    case "空闲":
      backgroundColor = "#00993340";
      break;
    case "已预定":
      backgroundColor = "#FFFF0040";
      break;
    case "已入住":
      backgroundColor = "#FF333390";
      break;
    case "打扫中":
      backgroundColor = "#00CCFF50";
      break;
  }
  return {
    backgroundColor: backgroundColor
  };
}
const dialogOpen = ref<boolean>(false); //对话框打开
const title = ref<string>("");

const roomNumber = ref("");
function checkInFrom(room) {
  roomNumber.value = room.roomNumber;
  dialogOpen.value = true;
}
const currentRoom = ref(null);

// 加载房间详细信息
const showInfoDialog = async roomNumber => {
  cardloading.value = true;
  currentRoom.value = null;
  try {
    console.log("roomNumber", roomNumber);
    const response = await getRoomCustomerInfo(roomNumber);
    currentRoom.value = response.data;
    console.log("currentRoom", response.data);
    cardloading.value = false;
  } catch (error) {
    console.error("获取房间信息失败:", error);
  }
};

function finishClean(roomNumber) {
  ElMessageBox.confirm(roomNumber + "号房间是否打扫完成?")
    .then(() => {
      return;
    })
    .then(() => {
      getList();
      ElMessage({ type: "success", message: "打扫完成" });
    })
    .catch(() => {
      console.log("打扫模块error");
    });
}
/** 关闭对话框 */
function handleCloseDialog() {
  dialogOpen.value = false;
  // roomTypesId.value = undefined;
  getList();
}
// 分页--> 修改每页数据数（5｜10｜20｜30）
function handleSizeChange(val: number) {
  queryParams.value.pageSize = val;
  getList();
}
//分页--> 修改当前页
function handleCurrentChange(val: number) {
  queryParams.value.pageNum = val;
  getList();
}

const checkOutStatus = reactive<RoomCheckOutStatus>({
  roomNumber: undefined,
  date: undefined
});
const checkedOutRooms = ref([]);
function getRoomCheckOutStatus() {
  getAllCheckOutStatus(queryParams.value.date).then(response => {
    console.log("checkOutStatus", response.data[0]);
    console.log("checkOutStatus", response.data[1]);
    checkedOutRooms.value = response.data;
  });
}
function handleCheckOut(room) {
  ElMessageBox.confirm(room + "号房间是否确认离店?").then(() => {
    console.log(typeof room === "string");
    roomCheckOut(room, queryParams.value.date)
      .then(response => {
        ElMessage({ type: "success", message: response.msg });
      })
      .then(() => {
        getList();
      })
      .catch(() => {
        console.log("离店模块error");
      });
  });
}
</script>

<style lang="scss" scoped>
.el-card:hover {
  cursor: pointer;
  transform: scale(1.02); /* 鼠标悬停时的缩放效果 */
}

.room-popover {
  padding: 10px;
}

.detail-item {
  display: flex;
  align-items: center;
  margin: 8px 0;
}

.detail-item label {
  min-width: 70px;
  margin-right: 10px;
  color: #666;
}

.detail-item span {
  font-size: 1500;
  font-weight: 500;
  color: #333;
}

.hover-scale {
  width: 25px;
  margin-left: 50px;
  cursor: pointer;
  transition: transform 0.2s; /* 添加过渡效果 */
}

.hover-scale:hover {
  transform: scale(1.25); /* 鼠标悬停时的缩放效果 */
}

.hover-human {
  margin-left: 90px;
  cursor: pointer;
  transition: transform 0.2s; /* 添加过渡效果 */
}

.hover-human:hover {
  transform: scale(1.25); /* 鼠标悬停时的缩放效果 */
}
</style>
